<template>
  <div class="checkout-container">
    <el-card class="checkout-card">
      <template #header>
        <div class="card-header">
          <h2>订单结算</h2>
        </div>
      </template>

      <el-steps :active="activeStep" finish-status="success" class="checkout-steps">
        <el-step title="确认订单" />
        <el-step title="选择支付方式" />
        <el-step title="完成支付" />
      </el-steps>

      <!-- 步骤1：确认订单 -->
      <div v-if="activeStep === 0">
        <div class="order-items">
          <el-table :data="cart" style="width: 100%">
            <el-table-column prop="dish.name" label="菜品" />
            <el-table-column prop="quantity" label="数量" width="100" />
            <el-table-column prop="dish.price" label="单价" width="100">
              <template #default="scope">
                ¥{{ scope.row.dish.price }}
              </template>
            </el-table-column>
            <el-table-column label="小计" width="100">
              <template #default="scope">
                ¥{{ scope.row.dish.price * scope.row.quantity }}
              </template>
            </el-table-column>
          </el-table>
        </div>

        <el-divider />

        <el-form :model="orderForm" label-width="100px" class="order-form">
          <el-form-item label="订单类型">
            <el-radio-group v-model="orderForm.order_type">
              <el-radio label="堂食">堂食</el-radio>
              <el-radio label="外卖">外卖</el-radio>
              <el-radio label="自取">自取</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item 
            label="配送地址" 
            v-if="orderForm.order_type === '外卖'"
          >
            <el-input 
              v-model="orderForm.address" 
              type="textarea" 
              placeholder="请输入详细地址"
            />
          </el-form-item>

          <el-form-item 
            label="桌号" 
            v-if="orderForm.order_type === '堂食'"
          >
            <el-input-number 
              v-model="orderForm.table_number" 
              :min="1" 
              :max="50"
            />
          </el-form-item>

          <el-form-item label="备注">
            <el-input 
              v-model="orderForm.note" 
              type="textarea" 
              placeholder="请输入特殊要求"
            />
          </el-form-item>
        </el-form>

        <div class="order-total">
          <span>总计：</span>
          <span class="total-price">¥{{ totalAmount }}</span>
        </div>
      </div>

      <!-- 步骤2：选择支付方式 -->
      <div v-if="activeStep === 1">
        <el-radio-group v-model="paymentMethod" class="payment-methods">
          <el-radio label="wechat">
            <el-icon><WechatFilled /></el-icon>
            微信支付
          </el-radio>
          <el-radio label="alipay">
            <el-icon><AlipayCircleFilled /></el-icon>
            支付宝
          </el-radio>
        </el-radio-group>
      </div>

      <!-- 步骤3：完成支付 -->
      <div v-if="activeStep === 2" class="payment-result">
        <el-result
          icon="success"
          title="支付成功"
          sub-title="您的订单已支付成功，我们将尽快为您准备"
        >
          <template #extra>
            <el-button type="primary" @click="goToOrders">查看订单</el-button>
            <el-button @click="goToMenu">继续点餐</el-button>
          </template>
        </el-result>
      </div>

      <div class="checkout-actions">
        <el-button @click="handleBack" v-if="activeStep > 0">
          上一步
        </el-button>
        <el-button 
          type="primary" 
          @click="handleNext"
          :loading="loading"
          v-if="activeStep < 2"
        >
          {{ activeStep === 1 ? '确认支付' : '下一步' }}
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { WechatFilled, AlipayCircleFilled } from '@element-plus/icons-vue'
import type { CartItem } from '../types'

const store = useStore()
const router = useRouter()
const activeStep = ref(0)
const loading = ref(false)
const paymentMethod = ref('wechat')

const cart = computed(() => store.state.cart)
const totalAmount = computed(() => {
  return cart.value.reduce((total, item) => {
    return total + item.dish.price * item.quantity
  }, 0)
})

const orderForm = ref({
  order_type: '堂食',
  address: '',
  table_number: 1,
  note: ''
})

const validateOrder = () => {
  if (orderForm.value.order_type === '外卖' && !orderForm.value.address) {
    ElMessage.warning('请填写配送地址')
    return false
  }
  if (cart.value.length === 0) {
    ElMessage.warning('购物车是空的')
    return false
  }
  return true
}

const handleNext = async () => {
  if (activeStep.value === 0 && !validateOrder()) {
    return
  }

  if (activeStep.value === 1) {
    // 创建订单并支付
    loading.value = true
    try {
      const orderData = {
        ...orderForm.value,
        items: cart.value.map(item => ({
          dish_id: item.dish.ID,
          quantity: item.quantity,
          price: item.dish.price
        }))
      }

      const response = await fetch('http://localhost:8080/api/orders', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${store.state.token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(orderData)
      })

      if (response.ok) {
        // 模拟支付过程
        await new Promise(resolve => setTimeout(resolve, 1000))
        store.commit('clearCart')
        activeStep.value++
      } else {
        ElMessage.error('创建订单失败')
      }
    } catch (error) {
      ElMessage.error('网络错误')
    } finally {
      loading.value = false
    }
  } else {
    activeStep.value++
  }
}

const handleBack = () => {
  activeStep.value--
}

const goToOrders = () => {
  router.push('/orders')
}

const goToMenu = () => {
  router.push('/menu')
}

onMounted(() => {
  if (cart.value.length === 0) {
    ElMessage.warning('购物车是空的')
    router.push('/menu')
  }
})
</script>

<style scoped>
.checkout-container {
  max-width: 1000px;
  margin: 20px auto;
  padding: 0 20px;
}

.checkout-card {
  margin-bottom: 20px;
}

.card-header {
  text-align: center;
}

.checkout-steps {
  margin: 20px 0 40px;
}

.order-items {
  margin: 20px 0;
}

.order-form {
  margin: 20px 0;
}

.order-total {
  text-align: right;
  margin: 20px 0;
  font-size: 18px;
}

.total-price {
  color: #f56c6c;
  font-size: 24px;
  font-weight: bold;
  margin-left: 10px;
}

.payment-methods {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 20px;
}

.payment-methods :deep(.el-radio) {
  height: 50px;
  line-height: 50px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 0 20px;
}

.payment-methods :deep(.el-radio.is-checked) {
  border-color: #409eff;
}

.checkout-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 40px;
}

.payment-result {
  padding: 40px 0;
}
</style> 